package com.firmail.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;
import java.util.UUID;

@Slf4j
public class FileKit {
    public static void copyFile(String src, String dest, boolean append) throws IOException {

        File file = new File(dest);
        if (file.isFile()) {
            if (!file.exists())
                file.createNewFile();
            else {
            /*if(overwite){
                if (file.delete()){
                    file.createNewFile();
                }else {
                    throw new IOException("删除文件失败，联系管理员处理。");
                }

            }*/
            }
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream(src);
                out = new FileOutputStream(file, append);
                int c;
                byte[] buffer = new byte[1024];
                while ((c = in.read(buffer)) != -1) {
                    out.write(buffer, 0, c);
                    //buffer = new byte[1024];
                }
            } finally {

                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
            }
        }
    }

    /**
     * overwite the origin file
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    public static void copyFile(String src, String dest) throws IOException {
        copyFile(src, dest, false);
    }

    public static void stringBufferWriteFile(StringBuffer srcBuffer, String dest, boolean append) throws IOException {
        FileOutputStream out = null;
        try {

            File file = new File(dest);
            if (!file.exists())
                file.createNewFile();
            out = new FileOutputStream(file, append);
            out.write(srcBuffer.toString().getBytes("utf-8"));

        } finally {
            if (out != null)
                out.close();
        }
    }

    //overwrite the file rather than append
    public static void stringBufferWriteFile(StringBuffer srcBuffer, String dest) throws IOException {
        stringBufferWriteFile(srcBuffer, dest, false);
    }

    public static void renameFile(String path, String oldname, String newname) {
        //新的文件名和以前文件名不同时,才有必要进行重命名
        if (!oldname.equals(newname)) {

            File oldfile = new File(path + File.separator + oldname);
            File newfile = new File(path + File.separator + newname);
            //若在该目录下已经有一个文件和新文件名相同，则不允许重命名
            if (newfile.exists())
                log.warn("Fail to rename the filename cause the New File {} exist.", newfile);
            else {
                oldfile.renameTo(newfile);
            }
        }
    }

    //move the dir
    public static void changeDirectory(String filename, String oldpath, String newpath, boolean cover) {
        if (!oldpath.equals(newpath)) {
            File oldfile = new File(oldpath + File.separator + filename);
            File newfile = new File(newpath + File.separator + filename);
            if (newfile.exists()) {//若在待转移目录下，已经存在待转移文件
                if (cover)//覆盖
                    oldfile.renameTo(newfile);
                else
                    log.warn("在新目录下已经存在：" + filename);
            } else {
                oldfile.renameTo(newfile);
            }
        }
    }

    public static String readFileInfo(String pathname) throws IOException {
        File file = new File(pathname);
        if (!file.exists() || file.isDirectory())
            throw new FileNotFoundException();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int b;
            StringBuffer sb = new StringBuffer();
            while ((b = fis.read(buf)) != -1) {
                sb.append(new String(buf, 0, b));
                //buf = new byte[1024];//重新生成，避免和上次读取的数据重复
            }
            return sb.toString();
        } finally {
            if (fis != null)
                fis.close();
        }
    }

    public static String readFileByBufferedReader(String path) throws IOException {
        File file = new File(path);
        if (!file.exists() || file.isDirectory())
            throw new FileNotFoundException();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String temp;
            StringBuffer sb = new StringBuffer();
            while ((temp = br.readLine()) == null) {
                sb.append(temp);
            }
            return sb.toString();
        } finally {
            if (br != null)
                br.close();
        }
    }

    public static boolean createDir(String path) {
        File dir = new File(path);
        if (!dir.exists())
            return dir.mkdirs();
        return false;
    }

    public boolean delFile(String path, String filename) {
        File file = new File(path + File.separator + filename);
        if (file.exists() && file.isFile())
            return file.delete();
        return false;
    }


    public static void recursiveDelDir(File dir) {
        //File dir=new File(path);
        if (dir.exists()) {
            File[] tmp = dir.listFiles();
            for (int i = 0; i < tmp.length; i++) {
                if (tmp[i].isDirectory()) {
                    recursiveDelDir(tmp[i]);
                } else {
                    tmp[i].delete();
                }
            }
            dir.delete();
        }
    }

    /**
     * 创建文件
     *
     * @param fileName    文件名称
     * @param filecontent 文件内容
     * @return 是否创建成功，成功则返回true
     */
    public static boolean createFile(String fullname, String filecontent) throws IOException {
        File file = new File(fullname);

        //如果文件不存在，则创建新的文件
        if (!file.exists()) {
            file.createNewFile();
        }
        log.info("success create file,the file is {}", file.getCanonicalPath());
        //创建文件成功后，写入内容到文件里
        return writeFileContent(fullname, filecontent, true);

    }
    public static boolean createFile(String path, String fileName, String extension, String filecontent) throws IOException {
        return createFile(path + fileName + extension, filecontent);
    }

    /**
     * 向文件中写入内容
     *
     * @param filepath 文件路径与名称
     * @param newstr   写入的内容
     * @return
     * @throws IOException
     */
    public static boolean writeFileContent(String filepath, String newstr, boolean isReadOrigin) throws IOException {
        boolean bool;

        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路径(包括文件名称)
            StringBuffer buffer = new StringBuffer();
            if (isReadOrigin) {
                //将文件读入输入流
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String temp = "";
                //文件原有内容
                for (int i = 0; (temp = br.readLine()) != null; i++) {
                    // 行与行之间的分隔符 相当于“\n”
                    buffer.append(temp).append(System.getProperty("line.separator"));
                }
            }
            buffer.append(newstr);

            pw = new PrintWriter(new FileOutputStream(file));
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            log.info("success create file,the file is {}", file.getCanonicalPath());
            bool = true;

        } finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (br != null) {
                br.close();
            }
        }
        return bool;
    }


    public static void main(String[] args) throws IOException {
        UUID uuid = UUID.randomUUID();
        createFile("679ee423-8840-42a1-ad6e-a9be4c88303bmyfile.json", "我的梦说别停留等待,就让光芒折射泪湿的瞳孔,映出心中最想拥有的彩虹,带我奔向那片有你的天空,因为你是我的梦 我的梦");

        System.out.println(File.pathSeparator);
        System.out.println(File.separator);
        System.out.println(System.getProperty("path.separator"));
        byte[] oo = new byte[10];
        oo[0] = 'a';
        System.out.println(oo.length);
        System.out.println(Arrays.toString(oo));
    }

}
